/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 8/1/18
Time: 4:13 AM
 */

package com.ug_project.dict.engine.indextable

import java.nio.ByteBuffer
import java.nio.ByteOrder

abstract class Block(val indexTable: IndexTable, var blockId: Int = 0){
    companion object {
        const val size = 16
    }
    private val channel = indexTable.channel
    val bytes = ByteArray(16)
    val buffer = ByteBuffer.wrap(bytes).apply {
        order(ByteOrder.BIG_ENDIAN)
    }
    init {
        resetPositions()
        buffer.rewind()
        channel.read(buffer)
    }
    fun resetPositions(){
        channel.position((blockId * size + IndexTable.dataBlockStart).toLong())
        buffer.rewind()
    }
    protected fun autoWriteToChannel(action: ByteBuffer.() -> Unit){
        resetPositions()
        buffer.action()
        resetPositions()
        channel.write(buffer)
    }
    abstract fun writeToChannel()
    val isEmpty: Boolean get() = !indexTable.readBlockAllocated(blockId)
}